package utils;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

public class LoggerFactory {

    public static Logger getLoggerForServlet(GenericServlet servlet) throws IOException {
        //evaluate logger name and get the logger
        String servletName = servlet.getServletConfig().getServletName();
        String loggerName = servletName + " logger";
        Logger logger = Logger.getLogger(loggerName);

        //If there no handlers are already added, add file handler
        //TODO not sure in the correctness of the code
        if (logger.getHandlers().length == 0) {
            //get logging path and make sure it exists
            String logDirPath = servlet.getServletConfig().getInitParameter("logging-dir");
            /*if (logDirPath == null)
                return null;*/
            File logDir = new File(logDirPath);

            //If directory in settings is not absolute, prepend it with the server root.
            //In our situation it would be  .../webapps/dces/ directory. Generally it is not a good idea
            //to store logs under server documents root, so in deployment configuration one should set
            //absolute logging directory.
            if (!logDir.isAbsolute())
                logDir = new File(servlet.getServletContext().getRealPath("/") + "/" + logDirPath);

            if (!logDir.exists())
                logDir.mkdirs();

            String logFileName = logDir.getAbsolutePath() + "/" + servletName + "-%g.log";
            FileHandler handler = new FileHandler(logFileName, 0, 100);
            logger.addHandler(handler);
        }

        return logger;
    }
}
